import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { refreshToken } from '@/views/tmpt/auth/api/user.js'
import Cookies from 'js-cookie'
import {getRefreshToken} from '@/utils/auth'


// create an axios instance
const service = axios.create({
  // process.env.VUE_APP_BASE_API, // url = base url + request url, base url is 、dev-api now
  baseURL: process.env.VUE_APP_SERVER_URL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10 * 4000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const url = config.url
    if (url.indexOf('auth/oauth/token') !== -1) {
      config.headers['Authorization'] = 'Basic bWVuZ3h1ZWd1LXBjOm1lbmd4dWVndS1zZWNyZXQ='
    }else if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }else{
      config.headers['Authorization'] = 'Bearer no token'
    }
    return config
  },
  error => {
    // do something with request error
    //console.log(error) // for debug
    //console.log(JSON.stringify(error)) // for debug
    return Promise.reject(error)
  }
)

// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []

//
const failure = {
  'code': 0,
  'success': false
}

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
    */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {

        if (response.status !== 200) {
          console.log("error: "+response)
          return failure
        }

        const result = response.data

        // 登录页面，返回的是认证服务器的，返回token结构
        if (result.success === undefined) {
          return response
        }

        // refresh token
        const config = response.config
        if (result.map && result.map.code === 401) {
            if (!isRefreshing) {
                isRefreshing = true
                let data = {}
                data.grant_type = 'refresh_token'
                data.refresh_token = getRefreshToken()
                return refreshToken(data).then(result => {
                    if (result.success) {
                        const { access_token } = result.map
                        store.dispatch('user/refreshToken', result)
                        // 接着发上一个请求
                        config.baseURL = ''
                        // 已经刷新了token，将所有队列中的请求进行重试
                        requests.forEach(cb => cb(access_token))
                        // 重试完了别忘了清空这个队列（掘金评论区同学指点）
                        requests = []
                        return service(config)
                    }
                }).catch(error => {
                    //console.log(error)
                    Promise.reject(error)
                }).finally(() => {
                    isRefreshing = false
                })
            } else {
                // 正在刷新token，返回一个未执行resolve的promise
                return new Promise((resolve) => {
                    // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
                    requests.push((token) => {
                      config.baseURL = ''
                      config.headers['Authorization'] = token
                      resolve(service(config))
                    })
                })
            }
        }
        return result;

    },error => {
        console.log("error sending ---》")
        console.log(error)
        return failure
    }
)

export default service
